package com.hddx.dao;

import com.hddx.domain.Account;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Repository
public class AccountDaoImpl implements AccountDao{
    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Override
    // 重写addAccount方法，用于添加账户
    public int addAccount(Account account) {
        // 定义插入语句
        String sql="insert into account (username,balance) values(?,?)";
        // 定义插入参数
        Object [] obj = {account.getUsername(),account.getBalance()};
        // 执行插入语句，并返回影响的行数
        return jdbcTemplate.update(sql,obj);
    }

    @Override
    public int updateAccount(Account account) {
        String sql = "update account set username=?,balance = ? where id =?";
        Object [] obj = {account.getUsername(),account.getBalance(),account.getId()};
        return jdbcTemplate.update(sql,obj);
    }

    @Override
    public int deleteAccount(int id) {
        String sql = "delete from account where id = ?";
        return jdbcTemplate.update(sql,id);
    }
    @Override
    public Account findAccountById(int id){
        String sql = "select * from account where id = ?";
        RowMapper<Account> ar = new BeanPropertyRowMapper<>(Account.class);
        return jdbcTemplate.queryForObject(sql,ar,id);
    }
    @Override
    public List<Account> findAccount(){
        String sql = "select * from account";
        RowMapper<Account> ar = new BeanPropertyRowMapper<>(Account.class);
        return jdbcTemplate.query(sql,ar);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED,isolation = Isolation.DEFAULT,timeout = 1000,readOnly = false)
    public void transfer(String inter, String outer, double money) {
        String outSql = "update account set balance = balance - ? where username = ?";
        jdbcTemplate.update(outSql,money,outer);
        String inSql = "update account set balance = balance + ? where username = ?";
        jdbcTemplate.update(inSql,money,inter);
    }

}
